import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {PageContainer, ProDescriptions, ProTable,} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, message} from 'antd';
import React, {useRef, useState} from 'react';
import {SortOrder} from "antd/es/table/interface";
import {bindOrLifeUsingPost} from "@/services/easyapi/eUserCenter";
import {pageProjectUsingPost, saveProjectUsingPost} from "@/services/easyapi/eProject";
import DatasourceProjectOperation from "@/pages/ProjectTableList/components/DatasourceProjectOperation";
import AddModal from "@/pages/ProjectTableList/components/ProjectAddModal";

export enum UserOperationActions {
  BIND_USER = "bindUser",
  LIFT_USER = "liftUser",
  EMPOWER_USER = "empowerUser",
  REVOKE_USER = "revokeUser",
}

const ProjectTableList: React.FC = () => {
  const [datasourceOperationVisible, setDatasourceOperationVisible] = useState<boolean>(false);
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.ProjectVo>();
  const [selectedRowsState, setSelectedRows] = useState<API.ApiCenterUserVo[]>([]);
const [addModelVisible, setAddModalVisible] = useState<boolean>(false);
  const bindOrLifeUser = async (user: API.ApiCenterUserVo) => {
    const action = user.userStatues === 0 ? UserOperationActions.BIND_USER : UserOperationActions.LIFT_USER
    await bindOrLifeUsingPost({
      userId: user.id,
      action: action
    }).then(res => {
      actionRef.current?.reload();
    })
  }

// 定义列配置
  const columns: ProColumns<API.ProjectVo>[] = [
    {
      title: '项目ID',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
      hideInForm: true, // 如果不需要在表单中显示
    },
    {
      title: '项目名称',
      tooltip:'项目名称不能重复,新建项目后名称不能更改',
      dataIndex: 'projectName',
      valueType: 'text',
      formItemProps: {
        rules: [
          {required: true, message: '请输入项目名称'},

        ],
      },
    },
    {
      title: '项目描述',
      dataIndex: 'projectDesc',
      valueType: 'textarea',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {max:255,message:'最大长度不能超过255'},
          {min:2,message: '最小长度不能小于2'}
        ],
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      hideInForm:true,
      valueEnum: {
        0: { text: '初始化', status: 'default' },   // Initialized
        1: { text: '正常', status: 'success' },     // Normal (Success)
        2: { text: '禁用', status: 'warning' },     // Disabled (Warning)
        3: { text: '失败', status: 'error' },       // Failed (Error)
      },
    },
    {
      title: '创建人名称',
      hideInForm:true,
      dataIndex: 'createUserName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'dateTime',
      hideInForm:true,
      hideInSearch: true
    },
    {
      title: '更新人名称',
      hideInForm:true,
      dataIndex: 'updateUserName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '是否开启编排',
      dataIndex: 'openOrchestration',
      valueType: 'select',
      valueEnum: {
        0: {text: '否'},
        1: {text: '是'},
      },
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="operation"
          onClick={() => {
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          详情
        </a>,
        <a
          key="datasource"
          onClick={() => {
            setCurrentRow(record);
            setDatasourceOperationVisible(true);
          }}
        >
          数据源
        </a>]
    }
  ];

  return (
    <PageContainer>
      <ProTable<API.ProjectVo, API.ProjectPageParam>
        headerTitle={'项目列表'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [<Button key="add" type="primary" onClick={() => {
          setAddModalVisible(true)
        }}>新增项目</Button>]}
        request={async (params
          , sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const res = await pageProjectUsingPost({
            ...params
          } as API.UserPageParam);
          if (res.code === 200) {
            return {
              // @ts-ignore
              data: res?.data.records,
              success: true,
              // @ts-ignore
              total: res?.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />
      <DatasourceProjectOperation project={currentRow} visible={datasourceOperationVisible} onCancel={() => {
        setDatasourceOperationVisible(false)
      }}/>
      <AddModal  columns={columns} onCancel={()=>{setAddModalVisible(false)}} onSubmit={async (values)=>{
        await saveProjectUsingPost({
          openOrchestration:values.openOrchestration,
          projectDesc:values.projectDesc,
          projectName:values.projectName,
        }).then(res=>{
          if(res.code===200){
            message.success('添加成功');
            setAddModalVisible(false)
            actionRef.current?.reload()
          }else{
            message.error(res.msg)
          }
        }).catch(err=>{
          message.error('添加失败');
        })
      }} visible={addModelVisible}/>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.projectName && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.projectName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};
export default ProjectTableList;
